#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "iot_gpio.h"
#include "iot_uart.h"
#include "hi_uart.h"
#include "hi_io.h"
#include "hi_gpio.h"

#include "comm.h"
#include "car_test.h"

//should enable CONFIG_UART2_SUPPORT
#define UART_ID      (2)
#define UART_GPIO_11 (11)
#define UART_GPIO_12 (12)
#define BUFF_SIZE    (100)

void ParseUartCmd(char *cmd)
{
    if(cmd != NULL)
    {
        if(strcmp("forward", cmd) == 0) {
            set_car_status(CAR_STATUS_FORWARD);
        } else if(strcmp("backward", cmd) == 0) {
            set_car_status(CAR_STATUS_BACKWARD);
        } else if(strcmp("left", cmd) == 0) {
            set_car_status(CAR_STATUS_LEFT);
        } else if(strcmp("right", cmd) == 0) {
            set_car_status(CAR_STATUS_RIGHT);
        } else if(strcmp("stop", cmd) == 0) {
            set_car_status(CAR_STATUS_STOP);
        } else if(strcmp("step", cmd) == 0) {
            set_car_mode(CAR_MODE_STEP);
        } else if(strcmp("alway", cmd) == 0) {
            set_car_mode(CAR_MODE_ALWAY);
        } else {
            printf("ParseUartCmd: invalid cmd: %s\n", cmd);
        }
    }
}

void UartConfig(void)
{
    const IotUartAttribute uart_attr = {115200, 8, 1, 0, 0, 0, 0};

    IoTGpioInit(UART_GPIO_11);
    IoTGpioInit(UART_GPIO_12);

    unsigned int ret = IoTUartInit(UART_ID, &uart_attr);
    if (ret != 0) {
        printf("UartConfig Falied ErrorNo: %d\n", ret);
        return;
    }
    printf("UartConfig: OK\n");
}

void UartTask(void)
{
    unsigned int len = 0;
    unsigned char uartReadBuff[BUFF_SIZE] = {0};

    printf("UartTask: Begin\n");
    UartConfig();

    while (1) {
        memset(uartReadBuff, 0, BUFF_SIZE);
        len = IoTUartRead(UART_ID, uartReadBuff, BUFF_SIZE);
        if (len > 0) {
            printf("UartTask read len[%d]data[%s]\n", len, uartReadBuff);
            ParseUartCmd(uartReadBuff);
        } else {
            // printf("UartTask read data failed\n");
        }
        usleep(100000);
    }
    printf("UartTask: End\n");
}

static void UartTaskEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "UartTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 2048;
    attr.priority = 25;
    if(osThreadNew((osThreadFunc_t)UartTask, NULL, &attr) == NULL) {
        printf("[UartTaskEntry] Faild to create UartTask!\n");
    }
}
SYS_RUN(UartTaskEntry);
